import { defineStore } from "pinia";
import { encryptedSerializer } from "@/utils/jiami";

// 定义 WsStoreType 接口，表示 WebSocket Store 的状态类型
interface WsStoreType {
  socketFlag: boolean;
  repeatNum: number;
  heartFlag: boolean;
  resource: any;
  uid: any;
}

// 定义 WebSocket Store，使用 Pinia 状态管理库
export const useWsStore = defineStore("ws", {
  // 初始化 state
  state: (): WsStoreType => ({
    socketFlag: false,
    repeatNum: 10,
    heartFlag: false,
    resource: {},
    uid: null,
  }),

  // 定义 actions 用于修改 state
  actions: {
    // 设置 heartFlag 的值
    setHeartFlag(flag: boolean) {
      this.heartFlag = flag;
    },
    // 设置 socketFlag 的值
    setSocketFlag(flag: boolean) {
      this.socketFlag = flag;
    },
    // 设置 uid 的值
    setUid(id: any) {
      this.uid = id;
    },
    // 设置 resource 对象的某个 key 的值，支持重写和追加两种模式
    setResource(key: string, value: any, type: string = "rewrite") {
      if (type === "rewrite") {
        this.resource[key] = value;
      } else if (type === "append") {
        if (!this.resource[key]) {
          this.resource[key] = [];
        }
        if (Array.isArray(this.resource[key])) {
          this.resource[key].push(value);
        } else if (this.resource[key].constructor === Object) {
          this.resource[key] = {
            ...this.resource[key],
            ...value,
          };
        }
      }
    },
  },
  // 持久化配置，使用 encryptedSerializer 对状态进行加密存储
  persist: {
    serializer: encryptedSerializer,
    enabled: true,
    storage: localStorage,
  },
});

// 定义 StoreType 类型，表示 useStore 的返回类型
export type StoreType = ReturnType<typeof useWsStore>;